﻿exports.gzip = function (req, res, next) {
    const zlib = require('zlib');
       
    var received = 0
    var buffers = []
    
    req.on('data', onData)
    req.once('end', onEnd)
    req.once('error', callback)
    req.once('error', cleanup)
    req.once('close', cleanup)
    
    function callback(err,buf){
        if (err) return next(err);
        
        buf = buf.toString('utf8').trim();
        
        var first = buf[0];
        
        if (0 == buf.length) {
            return next(utils.error(400, 'invalid json, empty body'));
        }
        var strict = true;
        if (strict && '{' != first && '[' != first) return next(utils.error(400, 'invalid json'));
        try {
            req.body = JSON.parse(buf, null);
        } catch (err) {
            err.body = buf;
            err.status = 400;
            return next(err);
        }
        next();
    }

    function onData(chunk) {
        buffers.push(chunk)
        received += chunk.length
    }
    
    function onEnd() {
        var buf = Buffer.concat(buffers);
        buf = zlib.gunzipSync(buf);
        callback(null, buf)
        
        
        cleanup()
    }
    
    function cleanup() {
        received = buffers = null
        
        req.removeListener('data', onData)
        req.removeListener('end', onEnd)
        req.removeListener('error', callback)
        req.removeListener('error', cleanup)
        req.removeListener('close', cleanup)
    }
};